package com.example.demo.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * Created by lile on 2020/2/5.
 */
@Configuration
@MapperScan(value = "com.example.demo.dao.db",sqlSessionFactoryRef = "datasourcesqlSessionFactory") //配置扫描的包，区分开
public class DruidMysqlDb {


    @Value("${spring.datasource.druid.db1.mapperLocations}")
    private String configLocation;


    @Bean(name = "datasource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    @Primary //多个数据源必须有个primary
    public DruidDataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "datasourcesqlSessionFactory")
    @Primary //多个数据源必须有个primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource") DruidDataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 配置mapper的扫描，找到所有的mapper.xml映射文件
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources(configLocation);
        factoryBean.setMapperLocations(resources);
        return factoryBean.getObject();
    }
//
//    @Primary
//    @Bean(name = "datasourcetransaction")
//    public PlatformTransactionManager transactionManager(@Qualifier("datasource") DruidDataSource dataSource) throws Exception {
//        return new DataSourceTransactionManager(dataSource);
//    }
}
